package web.jsfBean;

import java.text.MessageFormat;
import java.util.ResourceBundle;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.bean.UserBean;
import web.constant.WebConstant;

public abstract class BaseJsfBean {

	protected final FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}

	protected final Application getApplication() {
		return getFacesContext().getApplication();
	}

	protected final HttpSession getSession(boolean parameter) {
		return (HttpSession) getFacesContext().getExternalContext().getSession(parameter);
	}

	protected final HttpServletRequest getRequest() {
		return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
	}

	protected final HttpServletResponse getResponse() {
		return (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
	}

	protected final ServletContext getServletContext() {
		return (ServletContext) getFacesContext().getExternalContext().getContext();
	}

	protected final String getRequestParameter(String parameter) {
		return (String) getFacesContext().getExternalContext().getRequestParameterMap().get(parameter);
	}

	protected final void addMessage(FacesMessage.Severity severity, String message) {
		getFacesContext().addMessage(null, new FacesMessage(severity, message, ""));
	}

	protected final String getResourceValue(String key, Object[] parameters) {
		String text = null;
		ResourceBundle resourceBundle = getApplication().getResourceBundle(getFacesContext(), WebConstant.VARIABLE_RESOURCE_BUNDLE);
		text = resourceBundle.getString(key);

		if (parameters != null) {
			MessageFormat messageFormat = new MessageFormat(text, getFacesContext().getViewRoot().getLocale());
			text = messageFormat.format(parameters).toString();
		}
		return text;
	}

	protected final UserBean getUserSession() {
		HttpSession session = getSession(false);
		UserBean userBean = (UserBean) session.getAttribute("userBean");
		return userBean;
	}

}